import { Component, ElementRef, OnDestroy, OnInit } from '@angular/core';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { FetchService } from '../../../core/net/fetch.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { isToday, format } from 'date-fns';
import { Topology, Rect } from 'topology-core';
import * as _ from 'lodash';
import { Options } from 'topology-core/options';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { DpReportOverviewComponent } from '../dp-report-overview/dp-report-overview.component';
import { CookieService } from 'ngx-cookie-service';

@Component({
    selector: 'app-dispatch-glc',
    templateUrl: './dispatch-glc.component.html',
    styleUrls: ['../dispatch-common.scss', './dispatch-glc.component.scss']
})

export class DispatchGlcComponent implements OnInit, OnDestroy {
    nzBodyStyle: any = {
        padding: '9px 20px 0'
    };
    applyModalShow = false;
    applyAmount: number;
    recordModalShow = false;
    dutyRecordModalShow = false;
    jqsbModalShow = false;
    jqsbForm: FormGroup;
    officeOption;
    manageId = JSON.parse(localStorage.userInfo).manageId;
    selectedValue = '1';
    options = [
        { name: '宁西公司跃进渠', value: '1' },
        { name: '西干渠管理处', value: '2' },
        { name: '红寺堡扬水管理处', value: '3' },
        { name: '秦汉渠管理处', value: '4' },
        { name: '盐环定扬水管理处', value: '5' },
        { name: '汉延渠管理处', value: '7' },
        { name: '惠农渠管理处', value: '8' },
        { name: '固海扬水管理处', value: '9' },
        { name: '唐徕渠管理处', value: '10' },
        { name: '沙坡头水务局', value: '11' },
        { name: '七星渠管理处', value: '12' }
    ];

    ghtTitle = '管理处概化图';
    centerTableData = [];
    centerTableWidthConfig = ['100px', '100px', '100px', '100px', '100px', '100px', '100px', '100px'];
    canvas: Topology;
    canvasOptions: Options = {};
    rect: Rect;
    hoverItem = {
        top: '0px',
        left: '0px',
        alertLevel: '-',
        waterLevel: '-',
        limitTraffic: '-',
        flow: '-'
    };
    infoShow = false;

    jskllModalShow = false;
    jskllReportSrc: SafeResourceUrl;

    glcData;

    // gate		闸门
    // gate_out 	退水闸
    // pump		泵站
    // ZZ			水位站
    // ZQ			水文站
    // text_h		水位
    // text_q		流量
    canalList = [];
    defaultCanal;
    barOpt: any = {
        color: ['#5793f3', '#d14a61', '#675bba'],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            }
        },
        legend: {
            data: [],
            bottom: 0
        },
        grid: {
            top: '12%',
            bottom: '10%',
            left: '6%',
            right: '4%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            axisLabel: {
                interval: 0,
                formatter: value => value.split('').join('\n')
            },
            data: []
        },
        yAxis: [
            {
                type: 'value',
                name: '流量(m³/s)',
                position: 'right',
                axisLine: {
                    lineStyle: {
                        color: '#d14a61'
                    }
                }
            },
            {
                type: 'value',
                name: '水位（m）',
                position: 'left',
                axisLine: {
                    lineStyle: {
                        color: '#5793f3'
                    }
                }
            }
        ],
        series: [
            {
                name: '水位',
                type: 'bar'
            },
            {
                name: '流量',
                type: 'line',
                yAxisIndex: 1
            }
        ]
    };
    barOptChange: any = {};

    iframeSrc: SafeResourceUrl;
    sessionId;

    constructor(
        private fb: FormBuilder,
        private message: NzMessageService,
        private fetchService: FetchService,
        private el: ElementRef,
        private sanitizer: DomSanitizer,
        private modalService: NzModalService,
        private cookie: CookieService
    ) {
        // this.sessionId = this.cookie.get('JSESSIONID') || '';
        this.jqsbForm = this.fb.group({
            title: [''],
            // objId: [''],
            info: ['']
        });
        if (this.manageId == '10001') {
            this.selectedValue = '2';
            this.ghtTitle = this.options.filter(item => item.value == '2')[0].name + '概化图';
        } else {
            this.selectedValue = this.manageId;
            this.ghtTitle = this.options.filter(item => item.value == this.manageId)[0].name + '概化图';
        }
        this.canalList = [
            {
                label: '渠道名称',
                value: 1
            }
        ];
        this.defaultCanal = this.canalList[0].value;
    }

    ngOnInit(): void {
        // window.addEventListener('resize', this.debounce(() => {
        //     this.onResize();
        // }, 500));
        // this.getHhsqTableData();
        // this.getMapData();
        // this.getOfficeOption();
        // this.queryJskll();
        // this.canalSelectionChange();
        const link = `http://172.30.134.242:9008/api/index?url=/wrs-web/%23/realtime-control/dispatch-glc?account=nxgs%26mnp=1`;
        this.iframeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(link);
    }

    ngOnDestroy(): void {
        // this.canvas.destroy();
    }

    // 防抖函数
    debounce(func, wait?, immediate?): any {
        let timeout;
        return () => {
            const context = this;
            const args = arguments;
            const later = () => {
                timeout = null;
                if (!immediate) {
                    func.apply(context, args);
                }
            };
            const callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) {
                func.apply(context, args);
            }
        };
    }

    // 窗口变化
    onResize() {
        console.log('windonw is resize');
        const h = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().height;
        const w = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().width; // 设置画布
        this.rect = this.canvas.getRect();
        if (this.rect.width / this.rect.height > w / h) {
            this.canvas.scale(w / this.rect.width * 0.9);
        } else {
            this.canvas.scale(h / this.rect.height);
        }
        this.canvas.translate(w / 2 - this.rect.center.x, h / 2 - this.rect.center.y);
    }

    selectChange(e): void {
        this.getMapData();
        this.getHhsqTableData();
        // this.topPannelData = this.topPannelDatas[this.selectedValue];
        this.ghtTitle = this.options.filter(item => item.value == e)[0].name + '概化图';
    }

    getOfficeOption(): void {
        this.fetchService.post<any>('schedule/actualDispatchMonData/list', {}).subscribe(res => {
            this.officeOption = res;
        });
    }

    getMapData(): void {
        this.fetchService.post<any>('schedule/actualDispatchMonData/data', { manageId: this.selectedValue }).subscribe(r => {
            this.glcData = r;
            this.fetchService.get<any>('assets/data/glcnew/' + this.selectedValue + '.json').subscribe(res => {
                const pens = res.pens;
                // 数据处理
                this.glcData.map(feature => {
                    for (const pen of pens) {
                        // 修改闸门颜色
                        if (pen.data.cid == feature.objId) {
                            pen.image = '/yjq_web/assets/images/ght/newicons/' + feature.objType + feature.status + '.png';
                        }
                        // 修改q
                        if (pen.data.cid == `${feature.objId}q`) {
                            pen.text = feature.flow ? feature.flow + 'm³/s' : '-m³/s';
                        }
                        // 修改h
                        if (pen.data.cid == `${feature.objId}h`) {
                            pen.text = feature.waterLevel ? feature.waterLevel + 'm' : '-m';
                        }
                    }
                });

                if (this.canvas) {
                    // 重置画布数据
                    this.canvas.open({
                        id: '',
                        version: '',
                        name: 'new空白文件',
                        desc: '',
                        image: '',
                        userId: '',
                        class: '',
                        component: false,
                        shared: false
                    });
                } else {
                    // 创建画布
                    this.canvasOptions.on = this.onMouseEvent.bind(this);
                    this.canvas = new Topology('topology-canvas', this.canvasOptions);
                }
                this.canvas.open(res);

                // 设置画布
                this.onResize();
            });
        });
    }

    // 概化图元素事件
    onMouseEvent(event: string, node: any) {
        if (event === 'moveInNode') {
            if (node.data != '' && (['ZZ', 'ZQ', 'gate', 'gate_out'].indexOf(node.data.type) > -1)) {
                console.log(event, node);
                this.infoShow = true;
                const yArr = [node.rotatedAnchors[0].y, node.rotatedAnchors[1].y, node.rotatedAnchors[2].y, node.rotatedAnchors[3].y];
                const featureH = _.max(yArr) - _.min(yArr);
                console.log(featureH);
                this.hoverItem.top = (node.rect.center.y - 120 - featureH / 2 + 10) + 'px';
                this.hoverItem.left = (node.rect.center.x - 76) + 'px';
                const nodeId = node.data.cid;
                this.glcData.map(item => {
                    if (item.objId == nodeId) {
                        this.hoverItem.alertLevel = item.alertLevel || '-';
                        this.hoverItem.flow = item.flow || '-';
                        this.hoverItem.limitTraffic = item.limitTraffic || '-';
                        this.hoverItem.waterLevel = item.waterLevel || '-';
                    }
                });
            }
        }
        if (event === 'moveOutNode') {
            this.infoShow = false;
            this.hoverItem.alertLevel = '-';
            this.hoverItem.flow = '-';
            this.hoverItem.limitTraffic = '-';
            this.hoverItem.waterLevel = '-';
        }
        if (event === 'node') {
            // alert(node.data.name + '被点击了');
        }
    }

    getDispatchCount(e): void {
        this.applyAmount = e;
    }

    openApplyModal(): void {
        this.applyModalShow = true;
    }

    getHhsqTableData(): void {
        this.fetchService.post<any>('schedule/wrsActualDispatchApply/staticData', { manageId: this.selectedValue }).subscribe(res => {
            this.centerTableData = res;
        });
    }

    onApplyCancel(): void {
        this.applyModalShow = false;
    }

    openRecordModal(): void {
        this.recordModalShow = true;
    }

    openDutyRecordModal(): void {
        this.dutyRecordModalShow = true;
    }

    openJqsbModal() {
        this.jqsbModalShow = true;
        this.jqsbForm.reset();
    }

    onJqsbConfirm() {
        this.modalService.confirm({
            nzTitle: '确认上报该警情？',
            nzContent: '',
            nzOnOk: () => {
                this.fetchService.post('schedule/actualDispatchWarning/add', this.jqsbForm.value).subscribe(res => {
                    this.message.success('操作成功！');
                    this.jqsbModalShow = false;
                });
            }
        });
    }

    queryJskll(): void {
        const year = new Date().getFullYear();
        const month = new Date().getMonth() + 1;
        const token = localStorage.token;
        const serverUrl = (window as any).environment.reportUrl;
        const link = `${serverUrl}preview?_u=wrs:骨干排水沟.ureport.xml&_t=3,6&year=${year}&month=${month}&token=${token}`;
        this.jskllReportSrc = this.sanitizer.bypassSecurityTrustResourceUrl(link);
    }

    /**
     * 打开报送一览弹窗
     */
    openReportModal(): void {
        const modal = this.modalService.create({
            nzTitle: '报送一览',
            nzContent: DpReportOverviewComponent,
            nzComponentParams: {
                mngType: 1
            },
            nzFooter: null,
            nzWidth: '1050',
            nzClassName: 'dispatch-modal',
            nzOnCancel: () => {
                modal.destroy();
            }
        });
    }

    canalSelectionChange(): void {
        this.fetchService.post<any>('base/wrsBrwaterCannal/listLast', {
            pageSize: 1000
        }).subscribe(res => {
            this.barOptChange = {
                xAxis: {
                    data: res['list'].map(item => {
                        return item['stadiaName'];
                    }),
                    axisLabel: {
                        interval: 0
                    }
                },
                series: [
                    {
                        name: '水位',
                        type: 'bar',
                        data: res['list'].map(item => {
                            return item['waterHeight'];
                        })
                    },
                    {
                        name: '流量',
                        type: 'line',
                        yAxisIndex: 1,
                        data: res['list'].map(item => {
                            return item['flux'];
                        })
                    }
                ]
            };
        });
    }
}
